package com.dlc.beijingrfid.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.BindView;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.adapter.BuCaoAdapter;
import com.dlc.beijingrfid.adapter.decoration.RecyclerSpace;
import com.dlc.beijingrfid.base.BaseActivity;
import com.dlc.beijingrfid.net.bean.OrderDetailBean;
import com.dlc.beijingrfid.net.bean.OrderWashDetailBean;
import com.dlc.beijingrfid.net.bean.WashOrderDetailBean;
import com.dlc.beijingrfid.net.exception.ErrorMsgException;
import com.dlc.beijingrfid.net.protocol.OrderProto;
import com.dlc.beijingrfid.net.protocol.StockProto;
import com.dlc.beijingrfid.net.protocol.base.HttpProtocol;
import com.dlc.commonlibrary.adapter.BaseRecyclerAdapter;
import com.dlc.commonlibrary.ble.BleWorker;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.widget.TitleBar;
import com.trello.rxlifecycle.android.ActivityEvent;
import java.util.ArrayList;
import java.util.List;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class BuCaoJiaoJieActivity extends BaseActivity {
    @BindView(R.id.titleBar)
    TitleBar titleBar;

    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.orderno)
    TextView orderno;
    @BindView(R.id.hotel)
    TextView hotel;
    private BuCaoAdapter mAdapter;
    private String ordernoData;
    private DoResultDialog doReadDialog,doResultDialog;
    private String[] totalNum; //扫描订单二维码获取到的所有rfid
    private ArrayList<String> RfList = new ArrayList<>();//手持机读取的所有rfid
    private ArrayList<String> dataList = new ArrayList<>();//扫描订单二维码获取到的所有rfid
    private StringBuilder mStringBuilder;
    private Handler mHandler = new Handler();
    BleWorker mBleWorker = new BleWorker();

    @Override
    protected int getLayoutID() {
        return R.layout.activity_bucao;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ordernoData = getIntent().getStringExtra("orderno");
        Log.e("MainA",ordernoData);
        titleBar.titleText.setText("布草交接");
        titleBar.leftExit(this);
        initRecyclerView();
        if(!TextUtils.isEmpty(ordernoData)){
            if(ordernoData.contains("W")){
                getOrderWashDetail();
            }else if (ordernoData.contains("D")){
                getOrderDeliveryDetail();
            }else if (ordernoData.contains("B")){
                getDetailData();
            }
        }
        doReadRFID();
        doResult();
        mBleWorker.setCallback(new BleWorker.ReadCallback() {
            @Override
            public void onReceiveData(ArrayList<String> rfList,int readNum) {
                RfList = rfList;
                doReadDialog.dismiss();
                doResultDialog.showResultAndDismiss(true, 1000);
                if (rfList.size() > 0) {
                    doResultDialog.dismiss();
                    startData(null, null);

                } else {
                    doResultDialog.setFailedText("讀取不到RFID");
                    doResultDialog.setFailedImage(R.mipmap.ic_error);
                    doResultDialog.showResultAndDismiss(false, 2000);
                }
            }

            @Override
            public void onDeviceDisconnected() {
                doReadDialog.dismiss();
                Intent intent = new Intent(BuCaoJiaoJieActivity.this,MainActivity.class);
                intent.putExtra("type","2");
                startActivity(intent);
                finish();
            }
            @Override
            public void onErrorNumber(int number) {
                if (number > 0) {
                    showOneToast("存在长度小于14的标签" + number + "个");
                }
            }
        });
    }
//rfids=0017187053B6,0001F1558064,0001F1557893,0001F15566ED,020991AFAB0B
    public void check(View view) {
        if (totalNum == null) {
            showToast("未获得订单数据");
            return;
        }
        doReadDialog.showWorking(true);
        mBleWorker.check();
       // test();

    }
    private void test(){
        String strings[] ={"0001D4CF76AE","0001ED52F9EC",
        };
        for (int i = 0;i < strings.length;i++){
            RfList.add(strings[i]);
        }
        startData(null, null);
    }
    //private ArrayList<String> rfidsList = new ArrayList<>();
    //private int cashCount = 0;//获取到的缓存区的数量
    //private int TYPE = 0;
    //private boolean isBleStop = false;
    //private void getData(){
    //
    //    cashCount = 0;
    //    TYPE = 1;
    //    isBleStop = true;
    //    if (RRUA100API.getInstance(new Handler()).getConnectDevice()!= null){
    //        doReadDialog.showWorking(true);
    //        RRUA100API.getInstance(new Handler()).A100_clear_inventory();
    //        RRUA100API.getInstance(new Handler()).A100_readStart();
    //        RRUA100API.getInstance(new Handler()).readValue(new RRUA100API.BleCallBack() {
    //            @Override
    //            public void readDatas(String data,int type) {
    //                if (type == 1||type == 2) {
    //                    doData(data);
    //                }else {
    //                    if (TYPE == 3) {
    //                        isBleStop = false;
    //                        data = data.replaceAll("\r|\n| ", "");
    //                        cashCount = Integer.parseInt(data);
    //                        LogPlus.e("返回的缓存数量=" + data);
    //                        judgeData();
    //                    }else if (TYPE == 2){
    //                        judgeData();
    //                    }
    //                }
    //            }
    //        });
    //    } else { //跳去连接页面
    //        showToast("未连接设备，跳到连接页面");
    //        Intent intent = new Intent(getActivity(),MainActivity.class);
    //        intent.putExtra("type", "2");
    //        startActivity(intent);
    //    }
    //}
    //
    //private void doData(String data){
    //    rfidsList.add(data);
    //    LogPlus.e("蓝牙数据 count=" + rfidsList.size() + "");
    //}
    //
    //private void judgeData() {
    //    runOnUiThread(new Runnable() {
    //        @Override
    //        public void run() {
    //            if (!isBleStop) {
    //                RfList.clear();
    //                if (rfidsList.size() > 0) {
    //                    if (rfidsList.size() == cashCount || TYPE == 2) {//获取到的缓存区数量相等或者是直接获取缓存数据
    //                        doReadDialog.dismiss();
    //                        doResultDialog.showResultAndDismiss(true, 1000);
    //                        for (String str : rfidsList) {
    //                            if (str.length() > 14) {
    //                                str = str.substring(str.length() - 12, str.length());
    //                                RfList.add(str);
    //                            }
    //                        }
    //                        doResultDialog.dismiss();
    //                        startData(null, null);
    //                    } else {
    //                        //ToastUtil.show(getContext(),"获取的数量不对应，直接获取读到的缓存rfid");
    //                        TYPE = 2;
    //                        rfidsList.clear();
    //                        RRUA100API.getInstance(new Handler()).A100_getSyncTagList();
    //                    }
    //                } else {
    //                    doResultDialog.setFailedText("读取不到RFID");
    //                    doResultDialog.setFailedImage(R.mipmap.ic_error);
    //                    doResultDialog.showResultAndDismiss(false, 2000);
    //                }
    //            }else {
    //                showToast("未连接设备，跳到连接页面");
    //                Intent intent = new Intent(getActivity(),MainActivity.class);
    //                intent.putExtra("type", "2");
    //                startActivity(intent);
    //            }
    //        }
    //    });
    //
    //}
    //
    //
    //
    //
    //private void doData(){
    //    int a = 0;
    //    ArrayList<String> reduceList = new ArrayList<>();//库存减少的数据
    //    ArrayList<String> addList = new ArrayList<>();//扫描增加的数据
    //    ArrayList<String> recordList1 = new ArrayList<>();
    //    ArrayList<String> recordList2 = new ArrayList<>();
    //    for(int i = 0;i < totalNum.length;i++){
    //        reduceList.add(totalNum[i]);
    //        dataList.add(totalNum[i]);
    //    }
    //    addList.addAll(RfList);
    //    if (reduceList != null&&reduceList.size()>0) {
    //        for (int i = 0; i < reduceList.size(); i++) {
    //            for (int j = 0; j < addList.size(); j++) {
    //                if (reduceList.get(i).equals(addList.get(j))) {
    //                    recordList1.add(reduceList.get(i));
    //                    recordList2.add(addList.get(j));
    //                    a++;
    //                }
    //            }
    //        }
    //    }
    //    for (int i = 0;i<recordList1.size();i++){
    //        reduceList.remove(recordList1.get(i));
    //    }
    //    for (int i = 0;i<recordList2.size();i++){
    //        addList.remove(recordList2.get(i));
    //    }
    //    startData(reduceList,addList);
    //
    //}

    private void startData(ArrayList<String> reduceList,ArrayList<String> addList){
        dataList.clear();
        for(int i = 0;i < totalNum.length;i++){
            dataList.add(totalNum[i]);
        }
        Intent intent = new Intent(BuCaoJiaoJieActivity.this, BuCaoResultActivity.class);
       // intent.putStringArrayListExtra("reduceList",  reduceList);
        //intent.putStringArrayListExtra("addList",  addList);
        intent.putStringArrayListExtra("dataList",  dataList);
        intent.putStringArrayListExtra("RfList",  RfList);
        intent.putExtra("orderno",ordernoData);
        startActivity(intent);
    }



    private void initRecyclerView() {
        mAdapter = new BuCaoAdapter();

        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, BaseRecyclerAdapter.CommonHolder holder,
                                    int position) {

            }
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.addItemDecoration(new RecyclerSpace(getResources(), 0, R.dimen.normal_24dp));
        mRecyclerView.setAdapter(mAdapter);
    }

    private void doReadRFID() {
        doReadDialog =
                DoResultDialog.newDialog(this).
                        setWorkingText(getString(R.string.read_rfid_ing))
                        .setSuccessImage(R.mipmap.ic_success)
                        .setSuccessText(getString(R.string.scan_over))
                        .setButton("完成扫描", new DoResultDialog.OnClickButtonListener() {
                            @Override
                            public void onClickButton(DoResultDialog dialog) {

                                mBleWorker.cancelCheck();
                            }
                        });

        doReadDialog.setCancelable(false);

    }
    private void doResult() {

        doResultDialog = DoResultDialog.newDialog(this)
                .setWorkingText(getString(R.string.commit_counting_result))
                .setSuccessImage(R.mipmap.ic_success)
                .setSuccessText(getString(R.string.commit_counting_result_success));

        doResultDialog.setCancelable(false);


    }

    public void getOrderWashDetail() {
        showLoadingDialog();
        OrderProto.get()
                .orderWashDetail(null,ordernoData)
                .subscribeOn(Schedulers.io())
                .compose(this.<WashOrderDetailBean>bindUntilEvent(ActivityEvent.DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WashOrderDetailBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showOneToast(e.getMessage());
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(WashOrderDetailBean bean) {
                        dismissLoadingDialog();
                        if (bean.getCode() == 1) {
                            if (bean.getData().getSpec_group() != null) {
                                List<OrderWashDetailBean.DataBean.SpecGroupBean> list = new ArrayList<OrderWashDetailBean.DataBean.SpecGroupBean>();
                                List<WashOrderDetailBean.DataBean.SpecGroupBean> listWash = bean.getData().getSpec_group();
                                for (WashOrderDetailBean.DataBean.SpecGroupBean bean1 :listWash){
                                    OrderWashDetailBean.DataBean.SpecGroupBean bean2 = new OrderWashDetailBean.DataBean.SpecGroupBean();
                                    bean2.count = bean1.getCount();
                                    bean2.spec = bean1.getSpec();
                                    bean2.spec_id = bean1.getSpec_id();
                                    bean2.title = bean1.getTitle();
                                    list.add(bean2);
                                }
                                totalNum = bean.getData().getRfids().split(",");
                                mAdapter.setNewData(list);
                                orderno.setText(bean.getData().getOrderno());
                                hotel.setText(bean.getData().getHotel());

                            }
                        }else {
                            showOneToast(bean.getMsg());
                        }
                    }
                });
    }

    public void getOrderDeliveryDetail() {
        showLoadingDialog();
        OrderProto.get()
                .orderDeliverDetail(null,ordernoData)
                .subscribeOn(Schedulers.io())
                .compose(this.<WashOrderDetailBean>bindUntilEvent(ActivityEvent.DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<WashOrderDetailBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showOneToast(e.getMessage());
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(WashOrderDetailBean bean) {
                        dismissLoadingDialog();
                        if (bean.getCode() == 1) {
                            if (bean.getData().getSpec_group() != null) {
                                List<OrderWashDetailBean.DataBean.SpecGroupBean> list = new ArrayList<OrderWashDetailBean.DataBean.SpecGroupBean>();
                                List<WashOrderDetailBean.DataBean.SpecGroupBean> listWash = bean.getData().getSpec_group();
                                for (WashOrderDetailBean.DataBean.SpecGroupBean bean1 :listWash){
                                    OrderWashDetailBean.DataBean.SpecGroupBean bean2 = new OrderWashDetailBean.DataBean.SpecGroupBean();
                                    bean2.count = bean1.getCount();
                                    bean2.spec = bean1.getSpec();
                                    bean2.spec_id = bean1.getSpec_id();
                                    bean2.title = bean1.getTitle();
                                    list.add(bean2);
                                }
                                mAdapter.setNewData(list);
                                orderno.setText(bean.getData().getOrderno());
                                hotel.setText(bean.getData().getHotel());
                                totalNum = bean.getData().getRfids().split(",");
                            }
                        }else {
                            showOneToast(bean.getMsg());
                        }
                    }
                });
    }



    private void getDetailData() {
        StockProto.get()
                .getBackOrderDetail("order_back_detail", ordernoData, new HttpProtocol.Callback<OrderDetailBean>() {
                    @Override
                    public void onSuccess(OrderDetailBean bean) {
                        dismissLoadingDialog();
                        if (bean.code == 1) {
                            if (bean.data.spec_group != null) {
                                List<OrderWashDetailBean.DataBean.SpecGroupBean> list = new ArrayList<OrderWashDetailBean.DataBean.SpecGroupBean>();
                                List<OrderDetailBean.DataBean.SpecGroupBean> listWash = bean.data.spec_group;
                                for (OrderDetailBean.DataBean.SpecGroupBean bean1 : listWash) {
                                    OrderWashDetailBean.DataBean.SpecGroupBean bean3 = new OrderWashDetailBean.DataBean.SpecGroupBean();
                                    bean3.count = bean1.count;
                                    bean3.spec = bean1.spec;
                                    bean3.spec_id = bean1.spec_id;
                                    bean3.title = bean1.title;
                                    list.add(bean3);
                                }
                                mAdapter.setNewData(list);
                                orderno.setText(bean.data.orderno);
                                hotel.setText(bean.data.hotel);
                                totalNum = bean.data.rfids.split(",");
                            }
                        } else {
                            showOneToast(bean.msg);
                        }

                    }

                    @Override
                    public void onFailed(int code, ErrorMsgException e) {
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        dismissLoadingDialog();
                    }
                });
    }
}
